from __future__ import print_function

import pycurl
import json
import cStringIO
import string
import logging


def shorten(url):
	c = pycurl.Curl()
	c.setopt(pycurl.URL, "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyBb0ty8iKz2pHz4xpVjHDLxOFaFXZ-sK0k")
	c.setopt(pycurl.POST, 1)
	c.setopt(c.HTTPHEADER, ['Content-Type: application/json'])
	body = json.dumps({'longUrl': url})
	bodyOutput = cStringIO.StringIO(body)
	c.setopt(pycurl.READFUNCTION, bodyOutput.read)
	c.setopt(pycurl.POSTFIELDSIZE_LARGE, len(body))
	buffer_body = cStringIO.StringIO()
	buffer_headers = cStringIO.StringIO()
	c.setopt(pycurl.WRITEFUNCTION, buffer_body.write)
	c.setopt(pycurl.HEADERFUNCTION, buffer_headers.write)
	c.perform()
	status = c.getinfo(pycurl.HTTP_CODE)
	headers = {}
	headerList = string.split(string.strip(buffer_headers.getvalue()),"\r\n")
	headers["status"] = headerList.pop(0) # this contains http/1.1 xxx xx
	for header in headerList:
	        parts = string.split(header, ":")
		try:
			headers[string.strip(parts[0])] = string.strip(parts[1])
		except:
			pass
	body = json.loads(buffer_body.getvalue())
	buffer_body.close()
	buffer_headers.close()
	c.close()
	if status != 200:
		return ({"status": False, "longURL": url, "httpStatus": status, "httpHeader": headerList, "httpBody": body})
	return ({"status": True, "longURL": url, "shortURL": body["id"], "httpStatus": status, "httpHeader": headerList, "httpBody": body})
